<?php


namespace App\Http\Controllers;

use QrCode;
use Ramsey\Uuid\Uuid;
use App\Models\Qrcodes;
use JWTAuth;
use Illuminate\Http\Request;

/**
 * 扫码登录
 *
 * @author litc
 */
class QrcodeController extends Controller {
    
    /**
     * @apiSampleRequest http://app57.test/qrcode
     * @api {post} /qrcode 生成二维码
     * @apiDescription 生成二维码
     * @apiGroup 二维码
     * @apiPermission none
     * @apiSuccess {String} message 二维码图片路径
     * @apiSuccess {String} s 二维码唯一标识
     * @apiSuccessExample {json} 成功:
     *     HTTP/1.1 201
     *     {
     *         "code": 0,
     *         "message": "",
     *          "s": "",
     *              
     *     }
     * @apiErrorExample {json} 失败:
     *     HTTP/1.1 422
     *     {
     *       "code": -1,
     *       "message": "错误提示"
     *     }
     */
    public function qrcode(Request $request) {
        $uuidObj = Uuid::uuid1();
        $uuid = str_replace('-', '', $uuidObj->toString());
        $path = 'upload/qrcode/'.date('Ymd');
        if(!file_exists(public_path($path))){
            @mkdir(public_path($path), 0766, true);
        }

        Qrcodes::create([
            'qruuid'=>$uuid,
            'expire_at'=> time() + 120
        ]);
        
        $codeStr = implode('&', [ $uuid, 'scancode' ]);
        $png = "{$path}/{$uuid}.png";
        QrCode::format('png')->margin(0)->encoding('UTF-8')->size(200)->merge('/public/v.png', .15)->generate($codeStr, public_path($png));
        
        return [ 'message'=> str_replace('upload/', '', $png), 's'=>$uuid ];
    }
    
    /**
     * @apiSampleRequest http://app57.test/verifycode
     * @api {post} /verifycode 二维码确认
     * @apiDescription 二维码确认授权
     * @apiGroup 二维码
     * @apiPermission none
     * @apiHeader {String} authorization  用户访问标识
     * @apiParam {String} op 操作 verify|cancel
     * @apiSuccess {String} token 二维码唯一标识
     * @apiSuccessExample {json} 成功:
     *     HTTP/1.1 201
     *     {
     *         "code": 0,
     *         "message": "",
     *              
     *     }
     * @apiErrorExample {json} 失败:
     *     HTTP/1.1 422
     *     {
     *       "code": -1,
     *       "message": "错误提示"
     *     }
     */
    public function verifyCode(Request $request) {
       // $expireAt = $request->input('expire');
        $uuid = $request->input('token');
        if(!$uuid) {
            return $this->error('非法请求');
        }
        $op = $request->input('op');
        if(!in_array($op, ['verify', 'cancel'])) {
            return $this->error('非法操作');
        }
        $user = $request->user();
        if(!$user) {
            return $this->error('用户还没登录');
        }
        
        $scanCode = Qrcodes::where(['qruuid'=>$uuid, 'status'=>0]);
        $model = $scanCode->first();
        if(!$model) {
            return $this->error('用户不存在');
        }
        if($op =='cancel') {
            $scanCode->update(['status'=>5]);
           return $this->success('取消成功');
        }
        $expireAt = $model->expire_at;
        if(time() > $expireAt) {
            $scanCode->update(['status'=> 2 ]);
            return $this->error('授权已过期');
        }
        $res = false;
        if($op =='verify') {
            // $token = JWTAuth::getToken()->get();
            $token = JWTAuth::fromUser($user);
            $data = [ 'user_id'=> $user->getAuthIdentifier(), 'user_token'=>$token ];
            $res = $scanCode->update($data);
        }
        
        if(!$res) {
            $this->error('扫码登录失败');
        }
    }
    

    
    /**
     * @apiSampleRequest http://app57.test/checkQruuid
     * @api {get} /checkQruuid 二维码心跳检测
     * @apiDescription 二维码心跳检测
     * @apiGroup 二维码
     * @apiPermission none
     * @apiSuccess {String} s 二维码唯一标识
     * @apiSuccessExample {json} 成功:
     *     HTTP/1.1 201
     *     {
     *         "code": 0,
     *         "message": "",
     *              
     *     }
     * @apiErrorExample {json} 失败:
     *     HTTP/1.1 422
     *     {
     *       "code": -1,
     *       "message": "错误提示"
     *     }
     */
    public function checkQruuid(Request $request) {
        
        $uuid = $request->input('s');
        
        $scanCode = Qrcodes::where(['qruuid'=>$uuid, 'status'=>1])->first();
        
        if(!($scanCode && $scanCode->user_id)) {
            
           return [ 'code'=>-1, 'message'=>'还未登录' ];
           
        }
        
        $scanCode->update([ 'status' => 4 ]); // 4 扫码成功
        
        return [ 'message'=>'登录成功', 'data'=> $scanCode->user_token ];
    }
    
}
